import { createSlice } from "@reduxjs/toolkit";
import { loginAPI, getProfileAPI } from "@/apis";
const userStore = createSlice({
  name: "user",
  initialState: {
    token: localStorage.getItem("token") || "",
    userInfo: {},
  },
  reducers: {
    settoken(state, actions) {
      state.token = actions.payload;
      localStorage.setItem("token", actions.payload);
    },
    setUserInfo(state, actions) {
      state.userInfo = actions.payload;
    },
    clearUserInfo(state) {
      state.userInfo = {};
      localStorage.removeItem("token");
      state.token = "";
    },
  },
});

const { settoken, setUserInfo, clearUserInfo } = userStore.actions;

const userReducer = userStore.reducer;

const feactchLogin = (LoginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(LoginForm);
    dispatch(settoken(res.data.token));
  };
};

const feactchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI();
    dispatch(setUserInfo(res.data));
  };
};

export { settoken, feactchLogin, feactchUserInfo, clearUserInfo };
export default userReducer;
